/**
 * 
 */
package sailing.ui.systemsetting;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import org.jdesktop.application.SingleFrameApplication;

import sailing.entity.Cashier;
import sailing.listener.DATA;
import sailing.listener.UI;
import sailing.managers.CashierManager;
import sailing.ui.AbstractJPanel;
import sailing.ui.base.TopTitlePanel;
import sailing.ui.model.CashierTableModel;
import sailing.ui.model.EditBtnCellEditor;
import sailing.ui.model.EditBtnCellRenderer;
import cjlite.logger.Logger;
import cjlite.utils.RandomUtils;
import cjlite.utils.Strings;

/**
 * @author kevin
 * 
 */
public class CashierMgtPanel extends AbstractJPanel {
	private static Logger logger = Logger.thisClass();

	private CashierTableModel cashierTableModel;
	private JButton addNewBtn;

	private JTable cashierTable;

	/**
	 * @param application
	 */
	public CashierMgtPanel(SingleFrameApplication application) {
		super(application);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see sailing.ui.AbstractJPanel#initialPanel()
	 */
	@Override
	protected void initialPanel() {
		this.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 0));
		this.setLayout(new BorderLayout(10, 10));
		//this.add(this.getTopTitlePanel(), BorderLayout.NORTH);
		this.add(new TopTitlePanel("经手人管理"), BorderLayout.NORTH);
		
		cashierTable = new JTable();
		cashierTableModel = new CashierTableModel(this.getApplication());

		cashierTable.setModel(cashierTableModel);
		cashierTable.setRowHeight(35);
		cashierTable.setIntercellSpacing(new Dimension(15, 5));
		cashierTableModel.updateModel();

		JScrollPane scrollpane = new JScrollPane(cashierTable);
		this.add(scrollpane, BorderLayout.CENTER);
		this.add(this.getSidebarPanel(), BorderLayout.EAST);
		
		DATA.addDataListener(cashierTableModel);
	}

	private JPanel getSidebarPanel() {
		JPanel panel = new JPanel();
		addNewBtn = new JButton();
		addNewBtn.setText("添加新经手人");
		addNewBtn.setMargin(new Insets(5, 30, 5, 30));
		addNewBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// String cashierName = JOptionPane.showInputDialog(CashierMgtPanel.this, "");

				Object cashierName = JOptionPane.showInputDialog(CashierMgtPanel.this, "请输入经手人的名称：\n\n", "经手人",
						JOptionPane.PLAIN_MESSAGE, null, null, null);

				if (cashierName == null) {
					// means cancel
					return;
				}
				String cashierNameStr = (String) cashierName;
				save(cashierNameStr);
			}
		});

		JCheckBox showhideEditBtn = new JCheckBox();
		showhideEditBtn.setText("显示隐藏编辑按钮");

		showhideEditBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				JCheckBox cb = (JCheckBox) e.getSource();
				logger.trace("checkbox is selected[{0}]", cb.isSelected());
				showHideEditBtn(cb.isSelected());
			}
		});

		Box bv = Box.createVerticalBox();
		bv.add(addNewBtn);
		bv.add(Box.createVerticalStrut(20));
		bv.add(showhideEditBtn);
		panel.add(bv);
		return panel;
	}

	protected void save(String cashierName) {
		if (!isNameLegal(cashierName)) {
			return;
		}

		CashierManager cm = this.getApplication().getContext().getIoc().getInstance(CashierManager.class);
		
		Cashier c = new Cashier();
		c.setId(RandomUtils.randomString16());
		c.setName(cashierName);

		if (cm.save(c)) {
			JOptionPane.showMessageDialog(CashierMgtPanel.this, "添加成功。");
			UI.refresh(CashierTableModel.class);
		} else {
			JOptionPane.showMessageDialog(CashierMgtPanel.this, "添加失败。");
		}

	}

	private boolean isNameLegal(String cashierName) {
		if (cashierName == null || cashierName.trim().length() == 0) {
			JOptionPane.showMessageDialog(this, "名字不合法，请重新添加。");
			return false;
		}

		CashierManager cm = this.getApplication().getContext().getIoc().getInstance(CashierManager.class);

		if (cm.isExist(cashierName)) {
			JOptionPane.showMessageDialog(this, Strings.concat("'", cashierName, "' 已经存在，请重新添加。"));
			return false;
		}

		return true;
	}

	protected void showHideEditBtn(boolean selected) {
		this.cashierTableModel.showEditBtn(selected);
		// this.customerTableModel.fireTableDataChanged();
		this.cashierTableModel.fireTableStructureChanged();
		if (selected) {
			this.cashierTable.getColumnModel().getColumn(1).setCellRenderer(new EditBtnCellRenderer("编辑", "删除"));
			EditBtnCellEditor editBtnCell = new EditBtnCellEditor("编辑", "删除");
			editBtnCell.addBtn1Listener(editAL);
			editBtnCell.addBtn2Listener(deleteAL);
			this.cashierTable.getColumnModel().getColumn(1).setCellEditor(editBtnCell);
		}
	}

	ActionListener editAL = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() instanceof EditBtnCellEditor) {
				EditBtnCellEditor ce = (EditBtnCellEditor) e.getSource();
				if (ce.getCellEditorValue() instanceof Cashier) {
					Cashier cc = (Cashier) ce.getCellEditorValue();
					logger.trace("edit Cashier '{0}'", cc.getName());

					Object cashierName = JOptionPane.showInputDialog(CashierMgtPanel.this, "请输入经手人的新名称：\n\n", "经手人",
							JOptionPane.PLAIN_MESSAGE, null, null, cc.getName());

					if (cashierName == null) {
						// means cancel
						return;
					}
					
					if(!isNameLegal((String) cashierName)){
						return;
					}
					
					cc.setName((String) cashierName);
					
					update(cc);
				}
			}
		}
	};

	ActionListener deleteAL = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() instanceof EditBtnCellEditor) {
				EditBtnCellEditor ce = (EditBtnCellEditor) e.getSource();
				if (ce.getCellEditorValue() instanceof Cashier) {
					Cashier cc = (Cashier) ce.getCellEditorValue();
					logger.trace("delete cashier '{0}'", cc.getName());
					int result = JOptionPane.showConfirmDialog(CashierMgtPanel.this,
							Strings.concat("确定要删除：'", cc.getName(), "' ?"), "提示", JOptionPane.YES_NO_OPTION);
					if (JOptionPane.YES_OPTION == result) {
						CashierManager cm = getApplication().getContext().getIoc().getInstance(CashierManager.class);

						cm.delete(cc);
						UI.refresh(CashierTableModel.class);
					}
				}
			}
		}
	};

	private JPanel getTopTitlePanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEtchedBorder());
		panel.setBackground(titleBgColor);
		panel.add(new JLabel("经手人管理"));
		return panel;
	}

	protected void update(Cashier cc) {
		CashierManager cm = getApplication().getContext().getIoc().getInstance(CashierManager.class);

		if (cm.update(cc)) {
			JOptionPane.showMessageDialog(CashierMgtPanel.this, "更新成功。");
			UI.refresh(CashierTableModel.class);
		} else {
			JOptionPane.showMessageDialog(CashierMgtPanel.this, "更新失败。");
		}

		UI.refresh(CashierTableModel.class);

	}

}
